<?php

namespace api\modules\v1\models\group;

use api\modules\v1\models\friend\Friend;
use api\modules\v1\models\user\User;
use common\models\CacheKeys;
use common\models\friend\FriendApply;
use common\models\Functions;
use common\models\im\Im;
use common\models\Status;
use common\models\user\UserUnusualLog;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

class GroupUser extends \common\models\group\GroupUser
{

    /**
     * 群成员列表
     * @return array
     */
    public function getList()
    {
        try {
            $user = Yii::$app->getUser()->getIdentity()->toArray();

            $page = (int) Yii::$app->request->get('page', 1);
            $size = (int) Yii::$app->request->get('size', 20);
            $groupTxCode = (string) Yii::$app->request->get('group_tx_code', "");
            $account = (string) Yii::$app->request->get('account', '');
            $identity = (string) Yii::$app->request->get('identity', 0);  // 1- 群主 2-管理员 3-普通成员

            if (!$groupTxCode) {
                throw new Exception('群信息不存在！');
            }

            $groupInfo = Group::getObjectOneByWhere(['tx_code' => $groupTxCode])->with([])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }

            $where = $andWhere = [];

            $where['group_id'] = $groupInfo['id'];
            if ($identity) {
                $where['user_type'] = $identity;
            }

            if ($account) {
                $andWhere[] = [
                    'or',
                    ['like', 'nick_name', $account],
                    ['like', 'business_card', $account],
                ];
            }

            $count = static::getCountByAndWhere($where, $andWhere);
            $data = static::setPageinationAPI($page, $size, $count);

            $offset = ($page - 1) * $size;
            $list = static::getObjectByAndWhere($where, $andWhere, ['*'], 'id ASC', $offset, $size)->with([
                'user' => function ($q) {
                    $q->select(['id', 'login_name', 'user_face', 'nick_name', 'tx_code', 'user_code']);
                },
            ])
                ->asArray()->all();
            //好友列表
            $friend = Friend::getObjectByWhere(['user_id' => $user['id']], '*')->indexBy('friend_id')->asArray()->all();

            $result = [];
            foreach ($list as $v) {
                $singleUserInfo = ArrayHelper::getValue($v, 'user', []);
                $result[] = [
                    'id' => (int) $v['id'],
                    'user_id' => (int) $v['user_id'],
                    'face' => static::getAvatar($singleUserInfo['user_face']),
                    'business_card' => $v['business_card'] ?: $singleUserInfo['nick_name'],
                    'user_code' => $v['user_code'],
                    'tx_code' => $v['user_tx_code'],
                    'group_id' => $v['group_id'] ?: 0,
                    'group_code' => $v['group_code'],
                    'group_tx_code' => $v['group_tx_code'],
                    'group_name' => $v['group_name'],
                    'group_image' => static::getImages($groupInfo['group_image']),
                    'identity' => $v['user_type'] ?: 0,
                    'red_packet_state' => $v['is_receive_red_packet'] ?? Status::COMMON_RADIO_NO,
                    'shut_up' => (int) $v['is_shut_up'] ?? Status::COMMON_RADIO_NO,
                    'not_disturbing' => $v['is_not_disturbing'] ?? Status::COMMON_RADIO_NO,  # 是否免打扰 1-是 2-否
                    'time' => $v['create_time'],
                    'mark' => $friend[$v['user_id']] ? $friend[$v['user_id']]['mark'] ?: '' : '',
                ];
            }

            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 获取成员信息
     * @return array
     */
    public function getInfo()
    {
        try {
            $user = Yii::$app->getUser()->getIdentity()->toArray();

            $groupTxCode = (string) Yii::$app->request->get('group_tx_code', "");
            $userId = Yii::$app->request->get('user_code', '');

            if (empty($groupTxCode)) {
                throw new Exception('参数错误');
            }

            if (empty($userId)) {
                throw new Exception('参数错误');
            }

            $groupInfo = Group::getObjectOneByWhere(['tx_code' => $groupTxCode])->with([])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }

            $currentGroupUserInfo = static::getObjectByWhere([
                'user_id' => $user['id'],
                'group_id' => $groupInfo['id'],
            ])->with([])->asArray()->one();
            if (empty($currentGroupUserInfo)) {
                throw new Exception('你不是该群成员,无法查看！');
            }

            $groupUserInfo = static::getObjectByWhere([
                'user_tx_code' => $userId,
                'group_id' => $groupInfo['id'],
            ])->with([
                'inviteUser' => function ($q) {
                    $q->select(['id', 'login_name', 'user_face', 'nick_name', 'tx_code', 'user_code']);
                },

                'user' => function ($q) {
                    $q->select(['id', 'login_name', 'user_face', 'nick_name', 'tx_code', 'user_code']);
                },
            ])->asArray()->one();
            $applyUser = ArrayHelper::getValue($groupUserInfo, 'user', []);
            $inviteUser = ArrayHelper::getValue($groupUserInfo, 'inviteUser', []);


            $data = [
                'id' => (int) $groupUserInfo['id'],
                'user_id' => (int) $applyUser['id'],
                'nick_name' => $groupUserInfo['business_card'] ?: '',
                'tx_code' => $applyUser['tx_code'],
                'user_code' => $applyUser['user_code'],
                'face' => static::getAvatar($applyUser['user_face']),

                'invite_user_id' => (int) $groupUserInfo['invite_user_id'],
                'invite_nick_name' => $inviteUser['nick_name'] ?: '',
                'invite_tx_code' => $inviteUser['tx_code'],
                'invite_user_code' => $inviteUser['user_code'],
                'invite_face' => static::getAvatar($inviteUser['user_face']),
            ];


            return Functions::formatRestAPI(0, '', $data);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 修改名片
     * @return array
     */
    public function updateBusinessCard()
    {
        $trans = static::getDb()->beginTransaction();

        try {

            $user = Yii::$app->getUser()->getIdentity()->toArray();

            $groupTxCode = (string) Yii::$app->request->post('group_tx_code', "");
            $content = Yii::$app->request->post('content', '');

            if (!$groupTxCode) {
                throw new Exception('参数错误！');
            }

            if (!$content) {
                throw new Exception('参数错误！');
            }

            $groupInfo = Group::getObjectOneByWhere(['tx_code' => $groupTxCode])->with([])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }

            if ($groupInfo['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('群已被封禁！');
            }

            $groupUserInfo = static::getObjectByWhere([
                'user_id' => $user['id'],
                'group_id' => $groupInfo['id'],
            ])->with([])->asArray()->one();
            if (empty($groupUserInfo)) {
                throw new Exception('你不是该群成员！');
            }

            $updateData['business_card'] = $content;
            $resUpdate = static::updateData($updateData, ['id' => $groupUserInfo['id']]);
            if ($resUpdate === false) {
                throw new Exception('修改失败！');
            }

            // 修改im信息
            $updateImGroupData['NameCard'] = $content;
            (new Im())->updateImGroupUser($groupInfo['tx_code'], $groupUserInfo['user_tx_code'], $updateImGroupData);


            $trans->commit();
            return Functions::formatRestAPI(0, '修改成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 修改红包状态
     * @return array
     */
    public function updateRedPacketState()
    {
        $trans = static::getDb()->beginTransaction();

        try {

            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $groupTxCode = (string) Yii::$app->request->post('group_tx_code', "");
            $state = Yii::$app->request->post('state', '');
            $userId = Yii::$app->request->post('user_code', []);

            if (!is_array($userId)) {
                $userIds = [$userId];
            } else {
                $userIds = $userId;
            }

            $userIds = array_unique($userIds);
            if (!$groupTxCode) {
                throw new Exception('参数错误！');
            }

            if (!$userIds) {
                throw new Exception('未知用户！');
            }

            if (!$state) {
                throw new Exception('参数错误！');
            }

            if (!in_array($state, [Status::COMMON_RADIO_YES, Status::COMMON_RADIO_NO])) {
                throw new Exception('参数错误！');
            }

            $groupInfo = Group::getObjectOneByWhere(['tx_code' => $groupTxCode])->with([])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }

            if ($groupInfo['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('群已被封禁！');
            }

            // 是否是管理员或者群主
            $handleGroupUser = static::getObjectByWhere([
                'user_id' => $user['id'],
                'group_id' => $groupInfo['id'],
            ])->with([])->asArray()->one();
            if (empty($handleGroupUser)) {
                throw new Exception('非法请求（你不是该群成员）！');
            }
            if ($handleGroupUser['user_type'] != Status::GROUP_USER_TYPE_HOME && $handleGroupUser['user_type'] != Status::GROUP_USER_TYPE_MANAGE) {
                throw new Exception('您不是群主或管理员，无法操作！');
            }


            $groupUserList = static::getObjectByWhere([
                'user_tx_code' => $userIds,
                'group_id' => $groupInfo['id'],
            ])->with([])->asArray()->all();

            $imGroupMemberList = [];
            foreach ($groupUserList as $groupUserInfo) {
                if (empty($groupUserInfo)) {
                    //                    throw new Exception('该用户不是该群成员！');
                    continue;
                }
                if ($groupUserInfo['user_type'] == Status::GROUP_USER_TYPE_HOME) {
                    //                    throw new Exception('该用户为群主，无法被操作！');
                    continue;
                }

                if ($groupUserInfo['user_type'] == Status::GROUP_USER_TYPE_MANAGE) {
                    //                    throw new Exception('该用户为管理员，无法被操作！');
                    continue;
                }

                if ($groupUserInfo['is_receive_red_packet'] == $state) {
                    continue;
                }

                $updateData['is_receive_red_packet'] = $state;
                $resUpdate = static::updateData($updateData, ['id' => $groupUserInfo['id']]);
                if ($resUpdate === false) {
                    throw new Exception('修改失败！');
                }

                array_push($imGroupMemberList, $groupUserInfo['user_tx_code']);
            }


            // 更新im信息
            if ($imGroupMemberList) {
                $imModel = (new Im());
                $updateGroupUserDefineData['receive_red'] = (string) $state;
                foreach ($imGroupMemberList as $key => $value) {
                    $imModel->updateImGroupUser($groupInfo['tx_code'], $value, [], $updateGroupUserDefineData);
                }
                //                (new Im())->updateImGroupUser($groupInfo['tx_code'], $groupUserInfo['user_tx_code'],[],$updateGroupUserDefineData);
            }


            $trans->commit();
            return Functions::formatRestAPI(0, '修改成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 用户退群
     * @param string $groupTxCode
     * @return array
     */
    public function quitGroup($groupTxCode = '')
    {
        $trans = static::getDb()->beginTransaction();

        try {
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            CacheKeys::checkFrequency($user['id'], 1);

            $groupTxCode = $groupTxCode ? $groupTxCode : Yii::$app->request->post('group_tx_code', '');
            if (!$groupTxCode) {
                throw new Exception('参数错误！');
            }

            $groupInfo = Group::getObjectOneByWhere(['tx_code' => $groupTxCode])->with([])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }

            $groupUserInfo = static::getObjectByWhere([
                'user_id' => $user['id'],
                'group_id' => $groupInfo['id'],
            ])->with([
                'user' => function ($q) {
                    $q->select(['id', 'login_name', 'user_face', 'nick_name', 'tx_code', 'user_code']);
                }
            ])->asArray()->one();
            if (empty($groupUserInfo)) {
                throw new Exception('您已不在群中！');
            }
            if ($groupUserInfo['user_type'] == Status::GROUP_USER_TYPE_HOME) {
                throw new Exception('群主不可退群！');
            }

            // 群成员信息  与  群申请信息全都删除
            //            $resGroupUserDel = static::deleteAll(['id' => $groupUserInfo['id']]);
            $resGroupUserDel = static::deleteAll([
                'user_id' => $user['id'],
                'group_id' => $groupInfo['id'],
            ]);
            if (empty($resGroupUserDel)) {
                throw new Exception('退群失败！1');
            }

            $resGroupApplyDel = GroupApply::deleteAll([
                'group_id' => $groupInfo['id'],
                'user_id' => $groupUserInfo['user_id'],
            ]);
            //            if ($resGroupApplyDel === false) {
            //                throw new Exception('退群失败！2');
            //            }



            //            $trans->commit();

            // im退群
            $delImGroupUserData['GroupId'] = $groupInfo['tx_code'];
            $delImGroupUserData['Silence'] = 1; # 当 Silence 为1时，成员成功删除后，不会给任何人下发系统通知。
            $delImGroupUserData['MemberToDel_Account'] = [
                $user['tx_code'],
            ];

            $resDelImGroupUserData = (new Im())->delGroupUser($delImGroupUserData);
            if (!$resDelImGroupUserData) {
                throw new Exception('退群失败！');
            }

            // 修改群头像
            (new Group())->_updateGroupPic($groupInfo['id']);

            // 发送im消息
            $publicGroupMessage['message_type'] = Status::MESSAGE_TYPE_GROUP_PUBLIC;
            $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_QUIT_GROUP;  // 主动退出群聊
            $publicGroupMessage['oneTxCode'] = $groupUserInfo['user_tx_code'];
            $publicGroupMessage['oneNIckName'] = $groupUserInfo['user']['nick_name'];
            $publicGroupMessage['content'] = $groupUserInfo['user']['nick_name'] . "已退出群聊！";
            (new Im())->sendGroupMessage($groupInfo['tx_code'], $publicGroupMessage);

            $trans->commit();

            return Functions::formatRestAPI(0, '退群成功');
        } catch (\yii\db\Exception $ee) {
            $trans->rollBack();
            file_put_contents('/tmp/group_user.txt', "主动退群数据库失败:" . print_r($ee->getMessage(), true), FILE_APPEND);
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            file_put_contents('/tmp/group_user.txt', "主动退群失败时间" . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
            file_put_contents('/tmp/group_user.txt', "主动退群失败原因:" . print_r($e->getMessage(), true), FILE_APPEND);
            file_put_contents('/tmp/group_user.txt', "\n", FILE_APPEND);
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 邀请入群
     * @return array
     */
    public function inviteFriend()
    {
        $trans = static::getDb()->beginTransaction();

        try {
            $redis = Yii::$app->redis;
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            CacheKeys::checkFrequency("INVITE_GROUP_USER_" . $user['id'], 1);

            $groupTxCode = (string) Yii::$app->request->post('group_tx_code', "");
            $userCodes = Yii::$app->request->post('user_code', '');
            $userCodes = array_unique($userCodes);
            if (!$groupTxCode) {
                throw new Exception('未知群信息！');
            }

            if (empty($userCodes)) {
                throw new Exception('未知邀请好友信息！');
            }
            
            UserUnusualLog::checkUserUnusual($user['id'],Status::USER_UNUSUAL_TYPE_GROUP_CHAT);

            $groupInfo = Group::getObjectOneByWhere(['tx_code' => $groupTxCode])->with([])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }

            if ($groupInfo['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('群已被封禁！');
            }

            $groupUserInfo = static::getObjectByWhere([
                'user_id' => $user['id'],
                'group_id' => $groupInfo['id'],
            ])->with([
                'user' => function ($q) {
                    $q->select(['id', 'login_name', 'user_face', 'nick_name', 'tx_code', 'user_code']);
                }
            ])->asArray()->one();
            if (empty($groupUserInfo)) {
                throw new Exception('您已不在群中！');
            }

            $isManage = false;
            if ($groupUserInfo['user_type'] == Status::GROUP_USER_TYPE_HOME || $groupUserInfo['user_type'] == Status::GROUP_USER_TYPE_MANAGE) {
                $isManage = true;
            } else {
                if ($groupInfo['is_invite_friend'] == Status::COMMON_RADIO_NO) {
                    throw new Exception('该群不支持邀请好友！');
                }
            }


            $memberList = [];
            $imModel = new Im();
            $friendUsers = User::getObjectOneByWhere(['tx_code' => $userCodes])->with([
                'isFriend' => function ($q) use ($user) {
                    $q->where(['user_id' => $user['id']])->select(['id', 'friend_id', 'user_id']);
                },

                'isGroupUser' => function ($q) use ($groupInfo) {
                    $q->where(['group_id' => $groupInfo['id']])->select(['id', 'group_id', 'user_id']);
                },

                'isGroupApply' => function ($q) use ($groupInfo) {
                    $q->where([
                        'group_id' => $groupInfo['id'],
                        'status' => Status::COMMON_CHECKING_WAITING,
                    ])->select(['id', 'group_id', 'user_id']);
                },

            ])->asArray()->all();
            if (empty($friendUsers)) {
                throw new Exception('请选择需要邀请的好友！');
            }
            foreach ($friendUsers as $key => $friendUser) {
                if (empty($friendUser)) {
                    continue;
                }

                $isFriend = ArrayHelper::getValue($friendUser, 'isFriend', []);
                // 是否是好友
                if (empty($isFriend)) {
                    continue;
                }

                // 是否在群里
                $isGroupUser = ArrayHelper::getValue($friendUser, 'isGroupUser', []);
                if (!empty($isGroupUser)) {
                    continue;
                }

                // 是否已经邀请过
                $isGroupApply = ArrayHelper::getValue($friendUser, 'isGroupApply', []);

                // 申请信息 需要本人同意
                if (($friendUser['is_auto_enter_group'] == Status::COMMON_RADIO_NO || ($friendUser['is_auto_enter_group'] == Status::COMMON_RADIO_YES && !$isManage)) && $groupInfo['is_auto_enter'] == Status::COMMON_RADIO_NO
                ) {
                    // 需要本人同意
                    $groupApplyData = [];
                    if (empty($isGroupApply)) {
                        $groupApplyData['user_id'] = $friendUser['id'];
                        $groupApplyData['user_phone'] = $friendUser['login_name'];
                        $groupApplyData['user_code'] = $friendUser['user_code'];
                        $groupApplyData['user_nick_name'] = $friendUser['nick_name'];
                        $groupApplyData['user_face'] = $friendUser['user_face'];
                        $groupApplyData['user_tx_code'] = $friendUser['tx_code'];
                        $groupApplyData['enter_type'] = Status::GROUP_USER_JOIN_TYPE_INVITE; //1-申请进群  2-邀请进群 3-二维码
                        $groupApplyData['message'] = $user['login_name'] . "邀请进群";
                        $groupApplyData['status'] = Status::COMMON_CHECKING_WAITING;
                        $groupApplyData['group_id'] = $groupInfo['id'];;
                        $groupApplyData['group_code'] = $groupInfo['code'];
                        $groupApplyData['group_image'] = $groupInfo['image'];
                        $groupApplyData['group_name'] = $groupInfo['name'];
                        $groupApplyData['group_tx_code'] = $groupInfo['tx_code'];
                        $groupApplyData['create_time'] = date('Y-m-d H:i:s');
                        $groupApplyData['invite_user_id'] = $user['id'];
                        $groupApplyData['invite_user_phone'] = $user['login_name'];
                        $groupApplyData['invite_user_tx_code'] = $user['tx_code'];
                        $groupApplyData['invite_user_code'] = $user['user_code'];
                        $groupApplyData['be_invited_status'] = Status::COMMON_CHECKING_WAITING;
                        $groupApplyData['be_invited_status'] = $friendUser['is_auto_enter_group'] == Status::COMMON_RADIO_YES ? Status::COMMON_CHECKING_SUCCESS : Status::COMMON_CHECKING_WAITING;
                        $groupApplyRes = GroupApply::insertData($groupApplyData);
                        if ($groupApplyRes === false) {
                            throw new Exception('邀请失败！');
                        }
                    } else {
                        $groupApplyData['status'] = Status::COMMON_CHECKING_WAITING;
                        $groupApplyData['create_time'] = date('Y-m-d H:i:s');
                        $groupApplyRes = GroupApply::updateData($groupApplyData, ['id' => $isGroupApply['id']]);
                        if ($groupApplyRes === false) {
                            throw new Exception('邀请失败！');
                        }
                    }


                    if ($friendUser['is_auto_enter_group'] == Status::COMMON_RADIO_NO) {
                        // 发送个人邀请通知
                        FriendApply::notReadApplyNum($friendUser['id']);
                    }

                    if ($groupInfo['is_auto_enter'] == Status::COMMON_RADIO_NO) {
                        // 发送通知消息
                        FriendApply::notReadApplyNum(0,  $groupInfo['id']);
                    }
                }

                if (($friendUser['is_auto_enter_group'] == Status::COMMON_RADIO_YES && $isManage) || $groupInfo['is_auto_enter'] == Status::COMMON_RADIO_YES) {
                    // 群主或者管理员邀请   不需要本人同意 直接进群
                    $groupImInfo = $imModel->getGroupInfo($groupInfo['tx_code']);
                    if ($groupImInfo['MemberNum'] + 1 >  $groupImInfo['MaxMemberNum']) {
                        throw new Exception('该群人员已达上限！');
                    }
                    $groupUser = [];
                    $groupUser['group_id'] = $groupInfo['id'];
                    $groupUser['group_tx_code'] = $groupInfo['tx_code'];
                    $groupUser['group_code'] = $groupInfo['code'];
                    $groupUser['group_name'] = $groupInfo['name'];
                    //                    $groupUser['group_image'] = $groupInfo['image'];
                    $groupUser['user_id'] = $friendUser['id'];
                    $groupUser['user_tx_code'] = $friendUser['tx_code'];
                    $groupUser['user_face'] = $friendUser['user_face'];
                    $groupUser['user_nick_name'] = $friendUser['nick_name'];
                    //                    $groupUser['business_card'] = $friendUser['nick_name'];
                    $groupUser['business_card'] = '';
                    $groupUser['user_code'] = $friendUser['user_code'];
                    $groupUser['user_phone'] = $friendUser['login_name'];
                    $groupUser['user_type'] = Status::GROUP_USER_TYPE_NORMAL;
                    $groupUser['is_shut_up'] = Status::COMMON_RADIO_NO;   //禁言
                    $groupUser['is_not_disturbing'] = Status::COMMON_RADIO_NO;   //是否消息免打扰
                    $groupUser['is_receive_red_packet'] = Status::COMMON_RADIO_YES;  // 是否可以抢红包
                    $groupUser['create_time'] = date('Y-m-d H:i:s');
                    $groupUser['enter_type'] = Status::GROUP_USER_JOIN_TYPE_INVITE; //1-申请进群  2-邀请进群
                    $groupUser['invite_user_id'] = $user['id'];
                    $groupUser['invite_user_phone'] = $user['login_name'];
                    $groupUser['invite_user_tx_code'] = $user['tx_code'];
                    $groupUser['invite_user_code'] = $user['user_code'];
                    $groupUserRes = static::insertData($groupUser);
                    if ($groupUserRes === false) {
                        throw new Exception('进群失败！');
                    }

                    if ($isGroupApply) {
                        // 进群以后删除邀请记录
                        GroupApply::deleteAll(['id' => $isGroupApply['id']]);
                    }

                    $singleMember['Member_Account'] = (string) $friendUser['tx_code'];
                    $singleMember['NameCard'] = $friendUser['nick_name'];
                    $singleMember['enter_type'] = (string) Status::GROUP_USER_JOIN_TYPE_INVITE;
                    $singleMember['invite_code'] = (string) $user['tx_code'];
                    array_push($memberList, $singleMember);
                }
            }

            // 添加Im群成员
            if (!empty($memberList)) {
                //                $addImGroupRes = $imModel -> addGroupMember($groupInfo['tx_code'], $memberList);
                $addImGroupRes = $imModel->addImGroupUser($groupInfo['tx_code'], $memberList);
                if (!$addImGroupRes) {
                    throw new Exception('添加成员失败！');
                }

                $nickNameString = trim(implode(",", ArrayHelper::getColumn($memberList, 'NameCard')), ",");
                $txCodeString = trim(implode(",", ArrayHelper::getColumn($memberList, 'Member_Account')), ",");

                // 修改群头像
                (new Group())->_updateGroupPic($groupInfo['id']);

                // 发送im消息
                $publicGroupMessage['message_type'] = Status::MESSAGE_TYPE_GROUP_PUBLIC;
                $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_USER_INVITE_USER;   // 邀请进群
                $publicGroupMessage['oneTxCode'] = $user['tx_code'];
                $publicGroupMessage['oneNIckName'] = $user['nick_name'];
                $publicGroupMessage['twoTxCode'] = $txCodeString;
                $publicGroupMessage['towNIckName'] = $nickNameString;
                $publicGroupMessage['content'] = $user['nick_name'] . "邀请" . $nickNameString . "加入群聊！";
                $imModel->sendGroupMessage($groupInfo['tx_code'], $publicGroupMessage);
            }




            $trans->commit();
            return Functions::formatRestAPI(0, '邀请成功!');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 禁言 - 群成员禁言
     * @return array
     */
    public function shutUp()
    {
        $trans = static::getDb()->beginTransaction();

        try {
            $redis = Yii::$app->redis;
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            CacheKeys::checkFrequency($user['id'], 1);

            $groupTxCode = (string) Yii::$app->request->post('group_tx_code', "");
            $state = Yii::$app->request->post('state', 0);
            $userIds = Yii::$app->request->post('user_code', []);
            $userIds = array_unique($userIds);
            if (!$groupTxCode) {
                throw new Exception('参数错误！');
            }

            if (!$state) {
                throw new Exception('参数错误！');
            }

            if (!$userIds) {
                throw new Exception('参数错误！');
            }

            if (!in_array($state, [Status::COMMON_RADIO_YES, Status::COMMON_RADIO_NO])) {
                throw new Exception('禁言状态不合法！');
            }


            $groupInfo = Group::getObjectOneByWhere(['tx_code' => $groupTxCode])->with([])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }

            if ($groupInfo['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('群已被封禁！');
            }

            $groupUserInfo = static::getObjectByWhere([
                'user_id' => $user['id'],
                'group_id' => $groupInfo['id'],
            ])->with([])->asArray()->one();
            if (empty($groupUserInfo)) {
                throw new Exception('您已不在群中！');
            }

            if ($groupUserInfo['user_type'] != Status::GROUP_USER_TYPE_HOME && $groupUserInfo['user_type'] != Status::GROUP_USER_TYPE_MANAGE) {
                throw new Exception('您不是群主或管理，无法操作！');
            }

            $imGroupMemberList = [];
            $nickNameString = $txCodeString = '';

            $groupUserList = static::getObjectByWhere([
                'user_tx_code' => $userIds,
                'group_id' => $groupInfo['id'],
            ])->with([
                'user' => function ($q) {
                    $q->select(['id', 'login_name', 'user_face', 'nick_name', 'tx_code', 'user_code']);
                }
            ])->asArray()->all();
            if (empty($groupUserList)) {
                throw new Exception('请选择需要处理的群成员！');
            }
            foreach ($groupUserList as $key => $handleGroupUser) {
                $handleUser = ArrayHelper::getValue($handleGroupUser, 'user', []);
                if (empty($handleGroupUser)) {
                    continue;
                }

                if (empty($handleUser)) {
                    continue;
                }

                if (($handleGroupUser['user_type'] == Status::GROUP_USER_TYPE_MANAGE && $groupUserInfo['user_type'] == Status::GROUP_USER_TYPE_MANAGE) || $handleGroupUser['user_type'] == Status::GROUP_USER_TYPE_HOME) {
                    continue;
                }


                // 更新群成员
                $updateGroupUserData['is_shut_up'] = $state;
                $resGroupUserUpdate = static::updateData($updateGroupUserData, ['id' => $handleGroupUser['id']]);
                if ($resGroupUserUpdate === false) {
                    throw new Exception('操作失败！');
                }

                array_push($imGroupMemberList, $handleUser['tx_code']);

                $nickNameString .= $handleUser['nick_name'] . ',';
                $txCodeString .= $handleUser['tx_code'] . ',';
            }

            $imModel = new Im();
            if (!empty($imGroupMemberList)) {
                $updateImGroupUserData['GroupId'] = $groupInfo['tx_code'];
                $updateImGroupUserData['Members_Account'] = $imGroupMemberList;
                $updateImGroupUserData['ShutUpTime'] = $state == Status::COMMON_RADIO_YES ? '4294967295' : '0';
                $resUpdateImGroupUserData = $imModel->shutUpGroupUser($updateImGroupUserData);
                if (!$resUpdateImGroupUserData) {
                    throw new Exception('操作失败！');
                }

                // 更新im信息
                $updateGroupUserDefineData['is_shut_up'] = (string) $state;
                foreach ($imGroupMemberList as $key => $value) {
                    $imModel->updateImGroupUser($groupInfo['tx_code'], $value, [], $updateGroupUserDefineData);
                }
            }

            $nickNameString = trim($nickNameString, ",");
            $txCodeString = trim($txCodeString, ",");
            $publicGroupMessage['message_type'] = Status::MESSAGE_TYPE_GROUP_PUBLIC;
            $publicGroupMessage['oneTxCode'] = $user['tx_code'];
            $publicGroupMessage['oneNIckName'] = $user['nick_name'];
            $publicGroupMessage['twoTxCode'] = $txCodeString;
            $publicGroupMessage['towNIckName'] = $nickNameString;
            if ($state == Status::COMMON_RADIO_YES) {
                $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_SHUT_UP_USER_ON;
                $publicGroupMessage['content'] = "用户" . $user['nick_name'] . "已将用户:" . $nickNameString . '禁言！';
            } else {
                $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_SHUT_UP_USER_OFF;
                $publicGroupMessage['content'] = "用户" . $user['nick_name'] . "已取消用户:" . $nickNameString . '的禁言！';
            }
            (new Im())->sendGroupMessage($groupInfo['tx_code'], $publicGroupMessage);

            $trans->commit();
            return Functions::formatRestAPI(0, '操作成功');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 群聊踢人
     * @return array
     */
    public function kickOutGroup()
    {
        $trans = static::getDb()->beginTransaction();

        try {
            $redis = Yii::$app->redis;
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            CacheKeys::checkFrequency($user['id'], 1);
            $groupTxCode = (string) Yii::$app->request->post('group_tx_code', "");
            $userIds = Yii::$app->request->post('user_code', []);
            $userIds = array_unique($userIds);
            if (empty($groupTxCode)) {
                throw new Exception('参数错误！');
            }

            if (empty($userIds)) {
                throw new Exception('参数错误！');
            }


            $groupInfo = Group::getObjectOneByWhere(['tx_code' => $groupTxCode])->with([])->asArray()->one();
            if (empty($groupInfo)) {
                throw new Exception('群信息不存在！');
            }

            if ($groupInfo['status'] == Status::COMMON_RADIO_NO) {
                throw new Exception('群已被封禁！');
            }

            $groupUserInfo = static::getObjectByWhere([
                'user_id' => $user['id'],
                'group_id' => $groupInfo['id'],
            ])->with([])->asArray()->one();
            if (empty($groupUserInfo)) {
                throw new Exception('您已不在群中！');
            }

            if ($groupUserInfo['user_type'] != Status::GROUP_USER_TYPE_HOME && $groupUserInfo['user_type'] != Status::GROUP_USER_TYPE_MANAGE) {
                throw new Exception('您不是群主或管理，无法操作！');
            }

            $imGroupMemberList = [];
            $nickNameString = $txCodeString = '';
            $imGroupApplyModel = new GroupApply();

            $groupUserList = static::getObjectByWhere([
                'user_tx_code' => $userIds,
                'group_id' => $groupInfo['id'],
            ])->with([
                'user' => function ($q) {
                    $q->select(['id', 'login_name', 'user_face', 'nick_name', 'tx_code', 'user_code']);
                }
            ])->groupBy('user_id')->asArray()->all();
            if (empty($groupUserList)) {
                throw new Exception('请选择需要处理的群成员！');
            }

            foreach ($groupUserList as $key => $handleGroupUser) {
                $handleUser = ArrayHelper::getValue($handleGroupUser, 'user', []);
                if (empty($handleGroupUser)) {
                    continue;
                }

                if (empty($handleUser)) {
                    continue;
                }

                if (($handleGroupUser['user_type'] == Status::GROUP_USER_TYPE_MANAGE && $groupUserInfo['user_type'] == Status::GROUP_USER_TYPE_MANAGE) || $handleGroupUser['user_type'] == Status::GROUP_USER_TYPE_HOME) {
                    continue;
                }

                // 群成员信息  与  群申请信息全都删除
                //                $resGroupUserDel = static::deleteAll(['id' => $handleGroupUser['id']]);
                $resGroupUserDel = static::deleteAll([
                    'user_id' => $handleUser['id'],
                    'group_id' => $groupInfo['id'],
                ]);
                if (empty($resGroupUserDel)) {
                    throw new Exception('踢人失败！1');
                    continue;
                }

                $resGroupApplyDel = $imGroupApplyModel::deleteAll([
                    'group_id' => $groupInfo['id'],
                    'user_id' => $handleGroupUser['user_id'],
                ]);
                //                if ($resGroupApplyDel === false) {
                //                    throw new Exception('踢人失败！2');
                //                }


                array_push($imGroupMemberList, $handleUser['tx_code']);

                $nickNameString .= $handleUser['nick_name'] . ',';
                $txCodeString .= $handleUser['tx_code'] . ',';
            }

            //            $trans->commit();

            if (!empty($imGroupMemberList)) {
                // im退群
                $delImGroupUserData['GroupId'] = $groupInfo['tx_code'];
                $delImGroupUserData['Silence'] = 1; # 当 Silence 为1时，成员成功删除后，不会给任何人下发系统通知。
                $delImGroupUserData['MemberToDel_Account'] = $imGroupMemberList;

                $resDelImGroupUserData = (new Im())->delGroupUser($delImGroupUserData);
                if (!$resDelImGroupUserData) {
                    throw new Exception('踢出失败！');
                }
            }

            if (!empty($imGroupMemberList)) {
                // 修改群头像
                (new Group())->_updateGroupPic($groupInfo['id']);

                $nickNameString = trim($nickNameString, ",");
                $txCodeString = trim($txCodeString, ",");
                $publicGroupMessage['message_type'] = Status::MESSAGE_TYPE_GROUP_PUBLIC;
                $publicGroupMessage['oneTxCode'] = $user['tx_code'];
                $publicGroupMessage['oneNIckName'] = $user['nick_name'];
                $publicGroupMessage['twoTxCode'] = $txCodeString;
                $publicGroupMessage['towNIckName'] = $nickNameString;
                $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_USER_BE_KICK_OUT;
                $publicGroupMessage['content'] = "用户" . $user['nick_name'] . "已将:" . $nickNameString . '踢出群聊！';
                (new Im())->sendGroupMessage($groupInfo['tx_code'], $publicGroupMessage);
            }

            $trans->commit();

            return Functions::formatRestAPI(0, '操作成功');
        } catch (\yii\db\Exception $ee) {
            $trans->rollBack();
            file_put_contents('/tmp/group_user.txt', "T人数据库失败:" . print_r($ee->getMessage(), true), FILE_APPEND);
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            $trans->rollBack();
            file_put_contents('/tmp/group_user.txt', "T人失败时间" . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
            file_put_contents('/tmp/group_user.txt', "T人失败参数" . json_encode($_POST) . "\n", FILE_APPEND);
            file_put_contents('/tmp/group_user.txt', "T人失败原因:" . print_r($e->getMessage(), true), FILE_APPEND);
            file_put_contents('/tmp/group_user.txt', "\n", FILE_APPEND);
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
}
